package com.buka.listener;

import com.buka.api.OrderApi;
import com.buka.message.ProductMessage;
import com.buka.service.ProductTaskService;
import com.buka.util.JsonData;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Component
public class MQListener {

    @Resource
    ProductTaskService productTaskService;

    @RabbitListener(queues = "${mqconfig.stock_release_queue}")
    public void stockListener(ProductMessage productMessage, Message message, Channel channel) throws IOException {

        //获取到消息
        String outTradeNo = productMessage.getOutTradeNo();

        //查询订单状态
        boolean  b= productTaskService.releaseStock(productMessage);

        //操作库存  如果失败，消息应该也是拒绝消费的。

        //如果订单状态查询成功，操作库存，手动确认消息已消费
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        if(b){
            //消息的标识
            channel.basicAck(deliveryTag,false);//告诉MQ 那条消息消费成功
        }else{
            //拒绝消费，消息重新放入队列
            channel.basicReject(deliveryTag,true);
        }
    }
}
